﻿using System;
using System.Collections.Generic;

namespace RegionSplittor.Utils
{
	internal static class IEnumerableExtensions
	{
		public static tsource MinBy<tsource, tkey>(this IEnumerable<tsource> source, Func<tsource, tkey> selector)
		{
			return source.MinBy(selector, Comparer<tkey>.Default);
		}

		public static tsource MinBy<tsource, tkey>(this IEnumerable<tsource> source, Func<tsource, tkey> selector, IComparer<tkey> comparer)
		{
			if (source == null)
			{
				throw new System.ArgumentNullException("source == null");
			}
			if (selector == null)
			{
				throw new System.ArgumentNullException("selector == null");
			}
			if (comparer == null)
			{
				throw new System.ArgumentNullException("comparer == null");
			}
			tsource result;
			IEnumerator<tsource> enumerator = source.GetEnumerator();
			{
				if (!enumerator.MoveNext())
				{
					throw new InvalidOperationException("Sequence was empty");
				}
				tsource tsource2 = enumerator.Current;
				tkey y = selector(tsource2);
				while (enumerator.MoveNext())
				{
					tsource tsource3 = enumerator.Current;
					tkey tkey2 = selector(tsource3);
					if (comparer.Compare(tkey2, y) < 0)
					{
						tsource2 = tsource3;
						y = tkey2;
					}
				}
				result = tsource2;
			}
			return result;
		}
	}
}
